package jnpf.service.impl;

import jnpf.base.ActionResult;
import jnpf.entity.*;
import jnpf.mapper.KnowFileMangeMapper;
import jnpf.model.ragFlow.common.DocumentIdsReq;
import jnpf.model.ragFlow.common.RagFlowApiResult;
import jnpf.service.*;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jnpf.model.knowfilemange.*;

import java.math.BigDecimal;

import cn.hutool.core.util.ObjectUtil;
import jnpf.util.GeneraterSwapUtil;

import java.lang.reflect.Field;

import com.baomidou.mybatisplus.annotation.TableField;
import jnpf.model.QueryModel;

import java.util.stream.Collectors;

import jnpf.base.model.ColumnDataModel;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.core.metadata.IPage;
import jnpf.database.model.superQuery.SuperJsonModel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import jnpf.util.*;

import java.util.*;

import jnpf.base.UserInfo;
import jnpf.permission.entity.UserEntity;

/**
 * knowFileMange
 * 版本： V3.5
 * 版权： 引迈信息技术有限公司（https://www.jnpfsoft.com）
 * 作者： JNPF开发平台组
 * 日期： 2025-05-19
 */
@Service
public class KnowFileMangeServiceImpl extends ServiceImpl<KnowFileMangeMapper, KnowFileMangeEntity> implements KnowFileMangeService {
    @Autowired
    private GeneraterSwapUtil generaterSwapUtil;

    @Autowired
    private UserProvider userProvider;

    @Autowired
    private KnowFileMetadataService knowFileMetadataService;
    @Autowired
    private RagFlowFileService ragFlowFileService;

    @Override
    public List<KnowFileMangeEntity> getList(KnowFileMangePagination knowFileMangePagination) {
        return getTypeList(knowFileMangePagination, knowFileMangePagination.getDataType());
    }

    /**
     * 列表查询
     */
    @Override
    public List<KnowFileMangeEntity> getTypeList(KnowFileMangePagination knowFileMangePagination, String dataType) {
        String userId = userProvider.get().getUserId();
        List<String> AllIdList = new ArrayList();
        List<List<String>> intersectionList = new ArrayList<>();
        boolean isPc = ServletUtil.getHeader("jnpf-origin").equals("pc");
        String columnData = !isPc ? KnowFileMangeConstant.getAppColumnData() : KnowFileMangeConstant.getColumnData();
        ColumnDataModel columnDataModel = JsonUtil.getJsonToBean(columnData, ColumnDataModel.class);
        String ruleJson = !isPc ? JsonUtil.getObjectToString(columnDataModel.getRuleListApp()) : JsonUtil.getObjectToString(columnDataModel.getRuleList());

        int total = 0;
        int knowFileMangeNum = 0;
        QueryWrapper<KnowFileMangeEntity> knowFileMangeQueryWrapper = new QueryWrapper<>();
        int knowFileMetadataNum = 0;
        QueryWrapper<KnowFileMetadataEntity> knowFileMetadataQueryWrapper = new QueryWrapper<>();
        long knowFileMetadatacount = knowFileMetadataService.count();
        List<String> allSuperIDlist = new ArrayList<>();
        String superOp = "";
        if (ObjectUtil.isNotEmpty(knowFileMangePagination.getSuperQueryJson())) {
            List<String> allSuperList = new ArrayList<>();
            List<List<String>> intersectionSuperList = new ArrayList<>();
            String queryJson = knowFileMangePagination.getSuperQueryJson();
            SuperJsonModel superJsonModel = JsonUtil.getJsonToBean(queryJson, SuperJsonModel.class);
            int superNum = 0;
            QueryWrapper<KnowFileMangeEntity> knowFileMangeSuperWrapper = new QueryWrapper<>();
            knowFileMangeSuperWrapper = generaterSwapUtil.getCondition(new QueryModel(knowFileMangeSuperWrapper, KnowFileMangeEntity.class, queryJson, "0"));
            int knowFileMangeNum1 = knowFileMangeSuperWrapper.getExpression().getNormal().size();
            if (knowFileMangeNum1 > 0) {
                List<String> knowFileMangeList = this.list(knowFileMangeSuperWrapper).stream().map(KnowFileMangeEntity::getId).collect(Collectors.toList());
                allSuperList.addAll(knowFileMangeList);
                intersectionSuperList.add(knowFileMangeList);
                superNum++;
            }
            String knowFileMetadataTable = "file_metadata";
            boolean knowFileMetadataHasSql = queryJson.contains(knowFileMetadataTable);
            List<String> knowFileMetadataList = generaterSwapUtil.selectIdsByChildCondition(KnowFileMangeConstant.getTableList(), knowFileMetadataTable, queryJson, null);
            if (knowFileMetadataHasSql) {
                allSuperList.addAll(knowFileMetadataList);
                intersectionSuperList.add(knowFileMetadataList);
                superNum++;
            }
            superOp = superNum > 0 ? superJsonModel.getMatchLogic() : "";
            //and or
            if (superOp.equalsIgnoreCase("and")) {
                allSuperIDlist = generaterSwapUtil.getIntersection(intersectionSuperList);
            } else {
                allSuperIDlist = allSuperList;
            }
        }
        List<String> allRuleIDlist = new ArrayList<>();
        String ruleOp = "";
        if (ObjectUtil.isNotEmpty(ruleJson)) {
            List<String> allRuleList = new ArrayList<>();
            List<List<String>> intersectionRuleList = new ArrayList<>();
            SuperJsonModel ruleJsonModel = JsonUtil.getJsonToBean(ruleJson, SuperJsonModel.class);
            int ruleNum = 0;
            QueryWrapper<KnowFileMangeEntity> knowFileMangeSuperWrapper = new QueryWrapper<>();
            knowFileMangeSuperWrapper = generaterSwapUtil.getCondition(new QueryModel(knowFileMangeSuperWrapper, KnowFileMangeEntity.class, ruleJson, "0"));
            int knowFileMangeNum1 = knowFileMangeSuperWrapper.getExpression().getNormal().size();
            if (knowFileMangeNum1 > 0) {
                List<String> knowFileMangeList = this.list(knowFileMangeSuperWrapper).stream().map(KnowFileMangeEntity::getId).collect(Collectors.toList());
                allRuleList.addAll(knowFileMangeList);
                intersectionRuleList.add(knowFileMangeList);
                ruleNum++;
            }
            String knowFileMetadataTable = "file_metadata";
            boolean knowFileMetadataHasSql = ruleJson.contains(knowFileMetadataTable);
            List<String> knowFileMetadataList = generaterSwapUtil.selectIdsByChildCondition(KnowFileMangeConstant.getTableList(), knowFileMetadataTable, ruleJson, null);
            if (knowFileMetadataHasSql) {
                allRuleList.addAll(knowFileMetadataList);
                intersectionRuleList.add(knowFileMetadataList);
                ruleNum++;
            }
            ruleOp = ruleNum > 0 ? ruleJsonModel.getMatchLogic() : "";
            //and or
            if (ruleOp.equalsIgnoreCase("and")) {
                allRuleIDlist = generaterSwapUtil.getIntersection(intersectionRuleList);
            } else {
                allRuleIDlist = allRuleList;
            }
        }
        boolean pcPermission = false;
        boolean appPermission = false;
        if (isPc && pcPermission) {
            if (!userProvider.get().getIsAdministrator()) {
                Object knowFileMangeObj = generaterSwapUtil.getAuthorizeCondition(new QueryModel(knowFileMangeQueryWrapper, KnowFileMangeEntity.class, knowFileMangePagination.getMenuId(), "0"));
                if (ObjectUtil.isEmpty(knowFileMangeObj)) {
                    return new ArrayList<>();
                } else {
                    knowFileMangeQueryWrapper = (QueryWrapper<KnowFileMangeEntity>) knowFileMangeObj;
                    if (knowFileMangeQueryWrapper.getExpression().getNormal().size() > 0) {
                        knowFileMangeNum++;
                    }
                }
                Object knowFileMetadataObj = generaterSwapUtil.getAuthorizeCondition(new QueryModel(knowFileMetadataQueryWrapper, KnowFileMetadataEntity.class, knowFileMangePagination.getMenuId(), "0"));
                if (ObjectUtil.isEmpty(knowFileMetadataObj)) {
                    return new ArrayList<>();
                } else {
                    knowFileMetadataQueryWrapper = (QueryWrapper<KnowFileMetadataEntity>) knowFileMetadataObj;
                    if (knowFileMetadataQueryWrapper.getExpression().getNormal().size() > 0) {
                        knowFileMetadataNum++;
                    }
                }
            }
        }
        if (!isPc && appPermission) {
            if (!userProvider.get().getIsAdministrator()) {
                Object knowFileMangeObj = generaterSwapUtil.getAuthorizeCondition(new QueryModel(knowFileMangeQueryWrapper, KnowFileMangeEntity.class, knowFileMangePagination.getMenuId(), "0"));
                if (ObjectUtil.isEmpty(knowFileMangeObj)) {
                    return new ArrayList<>();
                } else {
                    knowFileMangeQueryWrapper = (QueryWrapper<KnowFileMangeEntity>) knowFileMangeObj;
                    if (knowFileMangeQueryWrapper.getExpression().getNormal().size() > 0) {
                        knowFileMangeNum++;
                    }
                }


                Object knowFileMetadataObj = generaterSwapUtil.getAuthorizeCondition(new QueryModel(knowFileMetadataQueryWrapper, KnowFileMetadataEntity.class, knowFileMangePagination.getMenuId(), "0"));
                if (ObjectUtil.isEmpty(knowFileMetadataObj)) {
                    return new ArrayList<>();
                } else {
                    knowFileMetadataQueryWrapper = (QueryWrapper<KnowFileMetadataEntity>) knowFileMetadataObj;
                    if (knowFileMetadataQueryWrapper.getExpression().getNormal().size() > 0) {
                        knowFileMetadataNum++;
                    }
                }


            }
        }
        if (isPc) {
            if (ObjectUtil.isNotEmpty(knowFileMangePagination.getTableField107_type())) {
                knowFileMetadataNum++;

                List<String> idList = new ArrayList<>();
                try {
                    String[][] type = JsonUtil.getJsonToBean(knowFileMangePagination.getTableField107_type(), String[][].class);
                    for (int i = 0; i < type.length; i++) {
                        if (type[i].length > 0) {
                            idList.add(JsonUtil.getObjectToString(Arrays.asList(type[i])));
                        }
                    }
                } catch (Exception e1) {
                    try {
                        List<String> type = JsonUtil.getJsonToList(knowFileMangePagination.getTableField107_type(), String.class);
                        if (type.size() > 0) {
                            idList.addAll(type);
                        }
                    } catch (Exception e2) {
                        idList.add(String.valueOf(knowFileMangePagination.getTableField107_type()));
                    }
                }
                knowFileMetadataQueryWrapper.lambda().and(t -> {
                    idList.forEach(tt -> {
                        t.like(KnowFileMetadataEntity::getType, tt).or();
                    });
                });

            }

            if (ObjectUtil.isNotEmpty(knowFileMangePagination.getTableField107_name())) {
                knowFileMetadataNum++;

                String value = knowFileMangePagination.getTableField107_name() instanceof List ? JsonUtil.getObjectToString(knowFileMangePagination.getTableField107_name()) : String.valueOf(knowFileMangePagination.getTableField107_name());
                knowFileMetadataQueryWrapper.lambda().like(KnowFileMetadataEntity::getName, value);

            }

            if (ObjectUtil.isNotEmpty(knowFileMangePagination.getTableField107_uptype())) {
                knowFileMetadataNum++;

                List<String> idList = new ArrayList<>();
                try {
                    String[][] uptype = JsonUtil.getJsonToBean(knowFileMangePagination.getTableField107_uptype(), String[][].class);
                    for (int i = 0; i < uptype.length; i++) {
                        if (uptype[i].length > 0) {
                            idList.add(JsonUtil.getObjectToString(Arrays.asList(uptype[i])));
                        }
                    }
                } catch (Exception e1) {
                    try {
                        List<String> uptype = JsonUtil.getJsonToList(knowFileMangePagination.getTableField107_uptype(), String.class);
                        if (uptype.size() > 0) {
                            idList.addAll(uptype);
                        }
                    } catch (Exception e2) {
                        idList.add(String.valueOf(knowFileMangePagination.getTableField107_uptype()));
                    }
                }
                knowFileMetadataQueryWrapper.lambda().and(t -> {
                    idList.forEach(tt -> {
                        t.like(KnowFileMetadataEntity::getValue, tt).or();
                    });
                });

            }

            if (ObjectUtil.isNotEmpty(knowFileMangePagination.getTableField107_datasetid())) {
                knowFileMetadataNum++;

                String value = knowFileMangePagination.getTableField107_datasetid() instanceof List ? JsonUtil.getObjectToString(knowFileMangePagination.getTableField107_datasetid()) : String.valueOf(knowFileMangePagination.getTableField107_datasetid());
                knowFileMetadataQueryWrapper.lambda().like(KnowFileMetadataEntity::getDatasetid, value);

            }

            if (ObjectUtil.isNotEmpty(knowFileMangePagination.getTableField107_ragfileid())) {
                knowFileMetadataNum++;

                String value = knowFileMangePagination.getTableField107_ragfileid() instanceof List ? JsonUtil.getObjectToString(knowFileMangePagination.getTableField107_ragfileid()) : String.valueOf(knowFileMangePagination.getTableField107_ragfileid());
                knowFileMetadataQueryWrapper.lambda().like(KnowFileMetadataEntity::getRagfileid, value);

            }

            if (ObjectUtil.isNotEmpty(knowFileMangePagination.getTableField107_ragdataid())) {
                knowFileMetadataNum++;

                String value = knowFileMangePagination.getTableField107_ragdataid() instanceof List ? JsonUtil.getObjectToString(knowFileMangePagination.getTableField107_ragdataid()) : String.valueOf(knowFileMangePagination.getTableField107_ragdataid());

            }

            if (ObjectUtil.isNotEmpty(knowFileMangePagination.getName())) {
                knowFileMangeNum++;

                String value = knowFileMangePagination.getName() instanceof List ? JsonUtil.getObjectToString(knowFileMangePagination.getName()) : String.valueOf(knowFileMangePagination.getName());
                knowFileMangeQueryWrapper.lambda().like(KnowFileMangeEntity::getName, value);

            }

            if (ObjectUtil.isNotEmpty(knowFileMangePagination.getBlocks())) {
                knowFileMangeNum++;

                List BlocksList = JsonUtil.getJsonToList(knowFileMangePagination.getBlocks(), String.class);
                for (int i = 0; i < BlocksList.size(); i++) {
                    String id = String.valueOf(BlocksList.get(i));
                    boolean idAll = StringUtil.isNotEmpty(id) && !id.equals("null");
                    if (idAll) {
                        BigDecimal b = new BigDecimal(id);
                        if (i == 0) {
                            knowFileMangeQueryWrapper.lambda().ge(KnowFileMangeEntity::getBlocks, b);
                        } else {
                            knowFileMangeQueryWrapper.lambda().le(KnowFileMangeEntity::getBlocks, b);
                        }
                    }
                }


            }

            if (ObjectUtil.isNotEmpty(knowFileMangePagination.getUptime())) {
                knowFileMangeNum++;

                List UptimeList = JsonUtil.getJsonToList(knowFileMangePagination.getUptime(), String.class);
                Long fir = Long.valueOf(String.valueOf(UptimeList.get(0)));
                Long sec = Long.valueOf(String.valueOf(UptimeList.get(1)));

                knowFileMangeQueryWrapper.lambda().ge(KnowFileMangeEntity::getUptime, new Date(fir)).le(KnowFileMangeEntity::getUptime, DateUtil.stringToDate(DateUtil.daFormatYmd(sec) + " 23:59:59"));


            }

            if (ObjectUtil.isNotEmpty(knowFileMangePagination.getType())) {
                knowFileMangeNum++;

                List<String> idList = new ArrayList<>();
                try {
                    String[][] type = JsonUtil.getJsonToBean(knowFileMangePagination.getType(), String[][].class);
                    for (int i = 0; i < type.length; i++) {
                        if (type[i].length > 0) {
                            idList.add(JsonUtil.getObjectToString(Arrays.asList(type[i])));
                        }
                    }
                } catch (Exception e1) {
                    try {
                        List<String> type = JsonUtil.getJsonToList(knowFileMangePagination.getType(), String.class);
                        if (type.size() > 0) {
                            idList.addAll(type);
                        }
                    } catch (Exception e2) {
                        idList.add(String.valueOf(knowFileMangePagination.getType()));
                    }
                }
                knowFileMangeQueryWrapper.lambda().and(t -> {
                    idList.forEach(tt -> {
                        t.like(KnowFileMangeEntity::getType, tt).or();
                    });
                });

            }

            if (ObjectUtil.isNotEmpty(knowFileMangePagination.getStatus())) {
                knowFileMangeNum++;

                List<String> idList = new ArrayList<>();
                try {
                    String[][] status = JsonUtil.getJsonToBean(knowFileMangePagination.getStatus(), String[][].class);
                    for (int i = 0; i < status.length; i++) {
                        if (status[i].length > 0) {
                            idList.add(JsonUtil.getObjectToString(Arrays.asList(status[i])));
                        }
                    }
                } catch (Exception e1) {
                    try {
                        List<String> status = JsonUtil.getJsonToList(knowFileMangePagination.getStatus(), String.class);
                        if (status.size() > 0) {
                            idList.addAll(status);
                        }
                    } catch (Exception e2) {
                        idList.add(String.valueOf(knowFileMangePagination.getStatus()));
                    }
                }
                knowFileMangeQueryWrapper.lambda().and(t -> {
                    idList.forEach(tt -> {
                        t.like(KnowFileMangeEntity::getStatus, tt).or();
                    });
                });

            }

            if (ObjectUtil.isNotEmpty(knowFileMangePagination.getHandle())) {
                knowFileMangeNum++;

                List<String> idList = new ArrayList<>();
                try {
                    String[][] handle = JsonUtil.getJsonToBean(knowFileMangePagination.getHandle(), String[][].class);
                    for (int i = 0; i < handle.length; i++) {
                        if (handle[i].length > 0) {
                            idList.add(JsonUtil.getObjectToString(Arrays.asList(handle[i])));
                        }
                    }
                } catch (Exception e1) {
                    try {
                        List<String> handle = JsonUtil.getJsonToList(knowFileMangePagination.getHandle(), String.class);
                        if (handle.size() > 0) {
                            idList.addAll(handle);
                        }
                    } catch (Exception e2) {
                        idList.add(String.valueOf(knowFileMangePagination.getHandle()));
                    }
                }
                knowFileMangeQueryWrapper.lambda().and(t -> {
                    idList.forEach(tt -> {
                        t.like(KnowFileMangeEntity::getHandle, tt).or();
                    });
                });

            }

            if (ObjectUtil.isNotEmpty(knowFileMangePagination.getDatasetid())) {
                knowFileMangeNum++;

                String value = knowFileMangePagination.getDatasetid() instanceof List ? JsonUtil.getObjectToString(knowFileMangePagination.getDatasetid()) : String.valueOf(knowFileMangePagination.getDatasetid());
                knowFileMangeQueryWrapper.lambda().like(KnowFileMangeEntity::getDatasetid, value);

            }

            if (ObjectUtil.isNotEmpty(knowFileMangePagination.getRagfileid())) {
                knowFileMangeNum++;

                String value = knowFileMangePagination.getRagfileid() instanceof List ? JsonUtil.getObjectToString(knowFileMangePagination.getRagfileid()) : String.valueOf(knowFileMangePagination.getRagfileid());
                knowFileMangeQueryWrapper.lambda().like(KnowFileMangeEntity::getRagfileid, value);

            }

        }
        if (knowFileMetadataNum > 0) {
            List<String> knowFileMetadataIdList = knowFileMetadataService.list(knowFileMetadataQueryWrapper).stream().filter(t -> StringUtil.isNotEmpty(t.getFileid())).map(t -> t.getFileid()).collect(Collectors.toList());
            long count = knowFileMetadataService.count();
            if (count > 0) {
                intersectionList.add(knowFileMetadataIdList);
            }
            AllIdList.addAll(knowFileMetadataIdList);
        }
        total += knowFileMetadataNum;
        List<String> intersection = generaterSwapUtil.getIntersection(intersectionList);
        if (total > 0) {
            if (intersection.size() == 0) {
                intersection.add("jnpfNullList");
            }
            knowFileMangeQueryWrapper.lambda().in(KnowFileMangeEntity::getId, intersection);
        }
        //是否有高级查询
        if (StringUtil.isNotEmpty(superOp)) {
            if (allSuperIDlist.size() == 0) {
                allSuperIDlist.add("jnpfNullList");
            }
            List<String> finalAllSuperIDlist = allSuperIDlist;
            knowFileMangeQueryWrapper.lambda().and(t -> t.in(KnowFileMangeEntity::getId, finalAllSuperIDlist));
        }
        //是否有数据过滤查询
        if (StringUtil.isNotEmpty(ruleOp)) {
            if (allRuleIDlist.size() == 0) {
                allRuleIDlist.add("jnpfNullList");
            }
            List<String> finalAllRuleIDlist = allRuleIDlist;
            knowFileMangeQueryWrapper.lambda().and(t -> t.in(KnowFileMangeEntity::getId, finalAllRuleIDlist));
        }

        //排序
        if (StringUtil.isEmpty(knowFileMangePagination.getSidx())) {
            knowFileMangeQueryWrapper.lambda().orderByDesc(KnowFileMangeEntity::getId);
        } else {
            try {
                String sidx = knowFileMangePagination.getSidx();
                String[] strs = sidx.split("_name");
                KnowFileMangeEntity knowFileMangeEntity = new KnowFileMangeEntity();
                Field declaredField = knowFileMangeEntity.getClass().getDeclaredField(strs[0]);
                declaredField.setAccessible(true);
                String value = declaredField.getAnnotation(TableField.class).value();
                knowFileMangeQueryWrapper = "asc".equals(knowFileMangePagination.getSort().toLowerCase()) ? knowFileMangeQueryWrapper.orderByAsc(value) : knowFileMangeQueryWrapper.orderByDesc(value);
            } catch (NoSuchFieldException e) {
                e.printStackTrace();
            }
        }

        if ("0".equals(dataType)) {
            if ((total > 0 && AllIdList.size() > 0) || total == 0) {
                Page<KnowFileMangeEntity> page = new Page<>(knowFileMangePagination.getCurrentPage(), knowFileMangePagination.getPageSize());
                IPage<KnowFileMangeEntity> userIPage = this.page(page, knowFileMangeQueryWrapper);
                return knowFileMangePagination.setData(userIPage.getRecords(), userIPage.getTotal());
            } else {
                List<KnowFileMangeEntity> list = new ArrayList();
                return knowFileMangePagination.setData(list, list.size());
            }
        } else {
            return this.list(knowFileMangeQueryWrapper);
        }
    }

    @Override
    public KnowFileMangeEntity getInfo(String id) {
        QueryWrapper<KnowFileMangeEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(KnowFileMangeEntity::getId, id);
        return this.getOne(queryWrapper);
    }

    @Override
    public void create(KnowFileMangeEntity entity) {
        this.save(entity);
    }

    @Override
    public boolean update(String id, KnowFileMangeEntity entity) {
        return this.updateById(entity);
    }

    @Override
    public void delete(KnowFileMangeEntity entity) {
        if (entity != null) {
            this.removeById(entity.getId());
        }
    }

    /**
     * KnowFileMetadata子表方法
     */
    @Override
    public List<KnowFileMetadataEntity> getKnowFileMetadataList(String id, KnowFileMangePagination knowFileMangePagination) {
        Map<String, Object> newtabMap = KnowFileMangeConstant.TABLEFIELDKEY.entrySet().stream().collect(Collectors.toMap(e -> e.getValue(), e -> e.getKey()));
        String tableName = "knowFileMetadata";
        tableName = newtabMap.get(tableName) == null ? tableName : newtabMap.get(tableName).toString();
        QueryWrapper<KnowFileMetadataEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper = knowFileMetadataService.getChild(knowFileMangePagination, queryWrapper);
        queryWrapper.lambda().eq(KnowFileMetadataEntity::getFileid, id);
        generaterSwapUtil.wrapperHandle(KnowFileMangeConstant.getColumnData(), KnowFileMangeConstant.getAppColumnData(), queryWrapper, KnowFileMetadataEntity.class, "sub", tableName);
        return knowFileMetadataService.list(queryWrapper);
    }

    /**
     * KnowFileMetadata子表方法
     */
    @Override
    public List<KnowFileMetadataEntity> getKnowFileMetadataList(String id) {
        QueryWrapper<KnowFileMetadataEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(KnowFileMetadataEntity::getFileid, id);
        return knowFileMetadataService.list(queryWrapper);
    }

    /**
     * 验证表单唯一字段，正则，非空 i-0新增-1修改
     */
    @Override
    public String checkForm(KnowFileMangeForm form, int i) {
        boolean isUp = StringUtil.isNotEmpty(form.getId()) && !form.getId().equals("0");
        String id = "";
        String countRecover = "";
        if (isUp) {
            id = form.getId();
        }
        //主表字段验证
        if (StringUtil.isEmpty(form.getName())) {
            return "名称不能为空";
        }
        //子表字段验证
        if (form.getKnowFileMetadataList() != null) {
        }
        return countRecover;
    }

    /**
     * 新增修改数据(事务回滚)
     *
     * @param id
     * @param knowFileMangeForm
     * @return
     */
    @Override
    @Transactional
    public void saveOrUpdate(KnowFileMangeForm knowFileMangeForm, String id, boolean isSave) throws Exception {
        UserInfo userInfo = userProvider.get();
        UserEntity userEntity = generaterSwapUtil.getUser(userInfo.getUserId());
        knowFileMangeForm = JsonUtil.getJsonToBean(generaterSwapUtil.swapDatetime(KnowFileMangeConstant.getFormData(), knowFileMangeForm), KnowFileMangeForm.class);
        KnowFileMangeEntity entity = JsonUtil.getJsonToBean(knowFileMangeForm, KnowFileMangeEntity.class);

        if (isSave) {
            String mainId = RandomUtil.uuId();
            entity.setId(mainId);
        } else {
        }
        this.saveOrUpdate(entity);

        //KnowFileMetadata子表数据新增修改
        if (!isSave) {
            QueryWrapper<KnowFileMetadataEntity> KnowFileMetadataqueryWrapper = new QueryWrapper<>();
            KnowFileMetadataqueryWrapper.lambda().eq(KnowFileMetadataEntity::getFileid, entity.getId());
            knowFileMetadataService.remove(KnowFileMetadataqueryWrapper);
        }
        if (knowFileMangeForm.getKnowFileMetadataList() != null) {
            List<KnowFileMetadataEntity> tableField107 = JsonUtil.getJsonToList(knowFileMangeForm.getKnowFileMetadataList(), KnowFileMetadataEntity.class);
            for (KnowFileMetadataEntity entitys : tableField107) {
                entitys.setId(RandomUtil.uuId());
                entitys.setFileid(entity.getId());
                if (isSave) {
                } else {
                }
                knowFileMetadataService.saveOrUpdate(entitys);
            }
        }
    }

    @Override
    @Transactional
    public ActionResult analysisFile(KnowFileMangeEntity entity) {
        ArrayList<String> ragfileList = new ArrayList<>();
        ragfileList.add(entity.getRagfileid());
        DocumentIdsReq documentIdsReq = new DocumentIdsReq();
        documentIdsReq.setDocument_ids(ragfileList);

        String handle = entity.getHandle();
        if ("1".equals(handle)) {
            return ActionResult.fail("文件正在解析中，请勿重复操作");
        } else if ("2".equals(handle)) {
            return ActionResult.fail("文件已解析完毕，无需再次解析");
        }

        // 判断 handle 字段是否为 0（未解析） 3解析失败
        if ("0".equals(handle) || "3".equals(handle)) {
            // 设置 handle 为 1（解析中）
            entity.setHandle("1");
            entity.setUpdatetime(new Date());
            entity.setUpdateuser(userProvider.get().getId());
            this.updateById(entity);

            try {
                RagFlowApiResult ragFlowApiResult = ragFlowFileService.parseDocuments(entity.getDatasetid(), documentIdsReq);
                if (ragFlowApiResult.getCode() == 0) {
                    return ActionResult.success("文件解析中");
//                    // 解析成功，设置 handle 为 2（已解析）
//                    entity.setHandle("2");
//                    entity.setUpdatetime(new Date());
//                    entity.setUpdateuser(userProvider.get().getId());
//                    this.updateById(entity);
//                    return ActionResult.success("文件解析成功");
                }else{
                    if(ragFlowApiResult.getMessage().contains("Documents not found")){
                        return ActionResult.fail("文件解析失败: RagFlow未找到该文件");
                    }else{
                        return ActionResult.fail("文件解析失败: " + ragFlowApiResult.getMessage());
                    }
                }
//                else {
//                    entity.setHandle("0");
//                    entity.setUpdatetime(new Date());
//                    entity.setUpdateuser(userProvider.get().getId());
//                    this.updateById(entity);
//                    return ActionResult.fail("文件解析失败:" + ragFlowApiResult.getMessage());
//                }
            } catch (Exception e) {
                // 解析失败，恢复 handle 为 0（未解析）
                entity.setHandle("0");
                entity.setUpdatetime(new Date());
                entity.setUpdateuser(userProvider.get().getId());
                this.updateById(entity);

            }
        }
        return ActionResult.fail("文件状态异常，无法进行解析操作");
    }
}
